const routes = require('koa-router')();
const axios = require('axios');
const qs = require('qs');
const config = require('../../config');

axios.defaults.headers.post['Content-Type'] =
    'application/x-www-form-urlencoded';
axios.defaults.transformRequest = function(data) {
    return qs.stringify(data);
};

function login(session, info) {
    session.user = {
        ...info
    };
}

// 用户登录
routes.post('/api/login', async function(ctx, next) {
    const { username, password } = ctx.request.body;

    await axios
        .post(`${config.authUrl}/ajaxLogin`, {
            username,
            password,
            state: 0
        })
        .then(res => {
            const { code, guid, token, name } = res.data;
            const data = { guid, token, username, name };
            if (code === 1000) {
                login(ctx.session, data);
            }

            ctx.body = res.data;
        });
});
// 用户退出
routes.post('/api/logout', function(ctx, next) {
    const data = {
        code: 1000,
        mesg: '',
        data: {}
    };

    ctx.body = data;
    ctx.session = null;

    // await axios.post(`${pdUrl}/logout`, qs.stringify({
    //     id: ctx.session.user.guid
    // }))
    // .then(function(res){
    //     if (res.data.code == 1000) {
    //         ctx.session = null;
    //     }
    //     ctx.body = res.data;
    // })
    // .catch(function(err){
    //     console.log('err', err);
    // })
});

module.exports = routes;
